package com.yu.transport.client;

import com.yu.util.InetSocketAddrUtil;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @PackageName: com.yu.transport.client
 * @Description: 保存/获取channel对象
 * @Version: v1.0.0
 * @Author: yuweilin
 * @Date: 16:24
 * <p>
 * Modification History:
 * Date         Author          Version            Description
 * ------------------------------------------------------------
 * 2021/2/5      yuweilin         v1.0.0               新建
 */
@Slf4j
public class ChannelProvider {
    private final Map<String, Channel> channelMap;

    public ChannelProvider() {
        channelMap = new ConcurrentHashMap<>();
    }

    /**
     * 通过一个地址对象，从map里面获取channel
     * 如果有，而且活跃，则返回channel
     * 否则返回null
     * @param inetSocketAddress
     * @return
     */
    public Channel get(InetSocketAddress inetSocketAddress){

        String key = InetSocketAddrUtil.getString(inetSocketAddress);
        if (channelMap.containsKey(key)){
            Channel channel = channelMap.get(key);
            if (channel!=null&&channel.isActive()){
                return channel;
            }else {
                channelMap.remove(key);
            }
        }
        return null;
    }

    /**
     *将地址对象和和一个channel对象传进来
     *然后将key和channel存入到map中
     * @param inetSocketAddress
     * @param channel
     */
    public void set(InetSocketAddress inetSocketAddress,Channel channel){
        String key = InetSocketAddrUtil.getString(inetSocketAddress);
        channelMap.put(key,channel);
    }
    

}
